import { createMD5 } from 'hash-wasm';

// 用于存储每个任务的状态和MD5生成器实例
const tasks = new Map();

self.addEventListener('message', async ({ data }) => {
  const { taskId, dataBuffer, status } = data;

  try {
    if (!taskId) {
      throw new Error('Task ID is required');
    }

    let makerInstance = tasks.get(taskId);

    if (status === 'create') {
      if (!makerInstance) {
        makerInstance = await createMD5();
        tasks.set(taskId, makerInstance);
      }
      makerInstance.init();
      self.postMessage({ taskId, status: 'createSuccess' });
    }

    if (status === 'ing' && makerInstance) {
      makerInstance.update(new Uint8Array(dataBuffer));
    }

    if (status === 'end' && makerInstance) {
      const md5 = makerInstance.digest();
      tasks.delete(taskId); // 清理任务状态
      self.postMessage({ taskId, md5, status: 'success' });
    }
  } catch (e) {
    self.postMessage({ taskId, status: 'error', error: (e as Error).toString() });
    console.error(e);
  }
});
